# MA策略
import talib
import module_backtest
from vnctptdType661 import *
from PyQt5 import QtCore
# CTP行情库
from vnctpmd import *
import numpy as np
import globalType
import globalvar

parlist = [['short', 3, 5, 1], ['long', 3, 5, 1]]


class MyStrategy(module_backtest.VirtualAccount, QtCore.QThread):
    def __init__(self, period, slippoint):
        super(MyStrategy, self).__init__(period, slippoint)
        self.close = []
        self.type = TradeType_VIRTUALACCOUNT
        '''
        self.period = period
        '''

    def InsertOrder(self, InstrumentID, exchangeid, direction, offside, VN_OPT_LimitPrice, price, vol):
        if self.type == TradeType_ACCOUNT:
            # 实盘
            globalvar.td.InsertOrder(InstrumentID, exchangeid, direction, offside, VN_OPT_LimitPrice, price, vol)
        elif self.type == TradeType_VIRTUALACCOUNT:
            # Python回测
            self.InsertOrder_backtest(InstrumentID, exchangeid, direction, offside, VN_OPT_LimitPrice, price, vol)

    def OnKline(self, reportpath1, reportpath2, mddata, arg, strategyname):
        if self.type == TradeType_VIRTUALACCOUNT:
            # 只有量化回测时才做处理，实盘交易不做处理
            super(MyStrategy, self).OnKline(reportpath1, reportpath2, arg, mddata)

        if arg[0] <= 0 or arg[1] <= 0:
            return

        # TradingDay = klinedata.TradingDay.decode()
        # klinetime = klinedata.klinetime.decode()
        self.InstrumentID = mddata.InstrumentID.decode()
        # self.exchange=mddata.exchange.decode()
        self.close.append(float(mddata.close))
        try:
            float_close = [float(x) for x in self.close]
        except Exception as e:
            pass
        self.MA_A = talib.MA(np.array(float_close), arg[0])
        self.MA_B = talib.MA(np.array(float_close), arg[1])
        # print('结果1:' + str(self.MA5))
        # print('结果2:' + str(self.MA20))
        if self.MA_A[len(self.MA_A) - 1] > self.MA_B[len(self.MA_B) - 1]:
            if self.sellvol + self.sellvol_history > 0:
                self.InsertOrder(self.InstrumentID, '', THOST_FTDC_D_Buy, THOST_FTDC_OF_Close, VN_OPT_LimitPrice,
                                 mddata.close + 1, 1)
            if self.buyvol + self.buyvol_history < 10:
                self.InsertOrder(self.InstrumentID, '', THOST_FTDC_D_Buy, THOST_FTDC_OF_Open, VN_OPT_LimitPrice,
                                 mddata.close + 1, 1)
        elif self.MA_A[len(self.MA_A) - 1] < self.MA_B[len(self.MA_B) - 1]:
            if self.buyvol + self.buyvol_history > 0:
                self.InsertOrder(self.InstrumentID, '', THOST_FTDC_D_Sell, THOST_FTDC_OF_Close, VN_OPT_LimitPrice,
                                 mddata.close - 1, 1)
            if self.sellvol + self.sellvol_history < 10:
                self.InsertOrder(self.InstrumentID, '', THOST_FTDC_D_Sell, THOST_FTDC_OF_Open, VN_OPT_LimitPrice,
                                 mddata.close - 1, 1)
